import 'dart:typed_data';

import 'package:encrypt/encrypt.dart';
import 'package:pointycastle/asymmetric/api.dart';

// https://github.com/leocavalcante/encrypt/blob/5.x/example/rsa.dart
// https://www.yisu.com/zixun/693513.html

final _parser = RSAKeyParser();

class EncryptUtil {
  /// Uint8List加密
  static Future<Uint8List> bytesEncrypt(String src, {required String key}) async {
    final encrypter = Encrypter(RSA(publicKey: (await publicKey(key))));
    return encrypter.encrypt(src).bytes;
  }

  /// Uint8List解密
  static Future<String> bytesDecrypt(Uint8List encoded, {required String key}) async {
    final encrypter = Encrypter(RSA(privateKey: (await privateKey(key))));
    return encrypter.decrypt(Encrypted(encoded));
  }

  /// base64加密
  static Future<String> base64Encrypt(String src, {required String key}) async {
    final encrypter = Encrypter(RSA(publicKey: (await publicKey(key))));
    return encrypter.encrypt(src).base64;
  }

  /// base64解密
  static Future<String> base64Decrypt(String encoded, {required String key}) async {
    final encrypter = Encrypter(RSA(privateKey: (await privateKey(key))));
    return encrypter.decrypt(Encrypted.from64(encoded));
  }

  /// 公钥
  static Future<RSAPublicKey> publicKey(String key) async {
    return _parser.parse(key) as RSAPublicKey;
  }

  /// 私钥
  static Future<RSAPrivateKey> privateKey(String key) async {
    return _parser.parse(key) as RSAPrivateKey;
  }
}
